import 'package:FlutterReader/reading/utils/show_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../helpers/database_helper.dart';
import '../../router/MyRouter.dart';
import '../../wights/status_view.dart';
import '../models/Book.dart';
import '../models/Chapter.dart';
import '../models/book_progress.dart';

class Read extends StatefulWidget with RouterBridge<Book> {
  const Read({super.key});

  @override
  State<Read> createState() => _ReadState();
}

class _ReadState extends State<Read> {
  String chapterTitle = "阅读界面";

  int bookId = 0;
  final db = DatabaseHelper();
  late List<Chapter> chapters = [];
  late BookProgress bookProgress;

  int currentChapter = 0; // 章节编码
  int chapterCode = 0;
  String fileContent = ""; // 章节内容
  double myFontSize = 16;

  List<String> pages = []; // 分页
  int pageSize = 0;
  int currentPage = 0;

  late ScrollController _scrollController;
  late final StatusViewController _controller;
  PageController _pageController = PageController();

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController(); // 初始化 ScrollController 定位用的
    _controller = StatusViewController(); // 初始化 StatusViewController 视图控制器

    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []); // 隐藏所有系统 UI 元素

    // _pageController.addListener(() {
    //   // 使用取整来获取当前页面的下标
    //   int newPage = _pageController.page!.round();
    //   if (newPage != currentPage) {
    //     print(newPage);
    //     setState(() {
    //       currentPage = newPage;
    //     });
    //   }
    // });
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final book = widget.argumentOf(context); // 替换为实际获取逻辑
    bookId = book?.id ?? 0;
    _loadChapters();
  }

  Future<void> _loadChapters() async {
    setState(() {
      _controller.showLoading(); // 开始加载
    });
    try {
      if(chapters.isEmpty){
        final result = await db.getProgressByBookId(bookId);
        bookProgress = BookProgress.fromMap(result);
        chapterCode = bookProgress.lastReadPage != -1 ? bookProgress.lastReadPage : 0;
        myFontSize = bookProgress.fontSize;
        final queryResult = await db.getChaptersByBookId(bookId);
        setState(() {
          chapters = queryResult.map((map) => Chapter.fromMap(map)).toList();
          if (chapters.isNotEmpty) {
            currentChapter = chapterCode; // 初始化到第一章
            fileContent = chapters[currentChapter].content ?? '默认值';
          }
        });
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("加载章节失败: $e")),
      );
    } finally {
      setState(() {
        _controller.loaded(); // 加载完成
      });
    }
  }

  @override
  Future<void> dispose() async {
    super.dispose();
    try {
      await db.updateProgress(bookProgress.toMap());
      // 恢复系统 UI
      SystemChrome.setEnabledSystemUIMode(
        SystemUiMode.edgeToEdge,
        overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom],
      );

      _pageController.dispose();
      _scrollController.dispose();
    } catch (e) {
      // 错误处理，例如记录日志
      print('Error updating progress: $e');
    }
  }

  void navigateToChapter(int index) {
    setState(() {
      currentChapter = index;
      chapterCode = currentChapter;
      bookProgress.lastReadPage = chapterCode;
      fileContent = chapters[currentChapter].content ?? "章节内容为空";
      _scrollToTop();
    });
  }

  void nextPage() {
    if (currentChapter < chapters.length - 1) {
      navigateToChapter(currentChapter + 1);
    }
    _pageController.jumpToPage(0);
  }

  void prePage() {
    if (currentChapter > 0) {
      navigateToChapter(currentChapter - 1);
    }

    int end = pageSize > 30? pageSize:30;
    _pageController.jumpToPage(end);
  }

  bool _isScrolling = false;
  void _scrollToTop() async {
    if (_isScrolling) return; // 防止重复调用
    _isScrolling = true;

    await _scrollController.animateTo(
      0.0,
      duration: Duration(milliseconds: 30),
      curve: Curves.easeOut,
    );
    _isScrolling = false;
  }

  Widget _buildChild() => ListView(
    padding: EdgeInsets.zero,
    children: <Widget>[
      DrawerHeader(
        decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage('assets/images/cover.png'),
              fit: BoxFit.cover
          ),
        ),
        child: Text(
          '书籍目录',
          style: TextStyle(
            fontSize: 24,
            color: Colors.white,
            shadows: [
              Shadow(
                color: Colors.black,
                offset: Offset(1, 1),
                blurRadius: 3,
              ),
            ],
          ),
        ),
      ),
      ..._buildMenuItems(),
    ],
  );

  List<Widget> _buildMenuItems() {
    return chapters.map((item) {
      return ListTile(
        leading: Icon(Icons.book_outlined),
        title: Text(item.title),
        onTap: () {
          navigateToChapter(chapters.indexOf(item)); // 跳转到对应章节
        },
      );
    }).toList();
  }

  late bool _showAppBar = true; // 控制 AppBar 是否显示
  void _toggleAppBar() {
    setState(() {
      _showAppBar = !_showAppBar; // 切换 AppBar 显示状态
    });
  }

  // 分页逻辑板块
  void splitContent(String text, BuildContext context) {
    final maxLinesPerPage = calculateMaxLinesPerPage(context);
    // print(maxLinesPerPage);
    pages = [];
    int start = 0;

    while (start < text.length) {
      final end = findNextPageEnd(text, start, maxLinesPerPage, context);
      pages.add(text.substring(start, end));
      start = end;
    }

    makePages();
  }
  int findNextPageEnd(String text, int start, int maxLines, BuildContext context) {
    final textPainter = TextPainter(
      text: TextSpan(text: text.substring(start), style: TextStyle(fontSize: myFontSize)), // 根据需要调整字体大小
      textDirection: TextDirection.ltr,
      maxLines: maxLines + 1, // 临时设置为 maxLines + 1，用于检测是否超出
    );

    textPainter.layout(maxWidth: MediaQuery.of(context).size.width); // 根据屏幕宽度布局

    if (textPainter.didExceedMaxLines) {
      // 如果超出最大行数，找到最后一个完整行的结束位置
      int end = start;
      for (int i = start; i < text.length; i++) {
        final subTextPainter = TextPainter(
          text: TextSpan(text: text.substring(start, i + 1), style: TextStyle(fontSize: myFontSize)),
          textDirection: TextDirection.ltr,
          maxLines: maxLines,
        );
        subTextPainter.layout(maxWidth: MediaQuery.of(context).size.width);

        if (!subTextPainter.didExceedMaxLines) {
          end = i + 1;
        } else {
          break;
        }
      }
      return end;
    } else {
      // 如果没有超出最大行数，返回文本的结尾
      return text.length;
    }
  }
  int calculateMaxLinesPerPage(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final lineHeight = myFontSize + 4;
    return (screenHeight / lineHeight).floor() - (30/lineHeight).ceil() - 10; // 减去一些边距
    // return 13;
  }
  var childrenPage = <Widget>[];
  void makePages(){
    childrenPage = <Widget>[];
    // 生成 n 个 Tab 页
    pageSize = pages.length;
    for (int i = 0; i < pageSize; ++i) {
      childrenPage.add( ShowPage( text: pages[i], myFontSize: myFontSize));
    }
  }
  Widget _pageViewShow(){
    String newFileContent = '\t\t\t\t${chapters[currentChapter].title}\n$fileContent';
    splitContent(newFileContent, context);

    return PageView(
      controller: _pageController,
      // scrollDirection: Axis.vertical, // 滑动方向为垂直方向
      children: childrenPage,
    );
  }

  // appbar上的功能组件
  void _showFontSizeDialog() {
    showDialog(
      context: context,
      builder: (context) {
        double tempFontSize = myFontSize; // 临时变量存储当前值
        return StatefulBuilder(
          builder: (context, setStateDialog) {
            return AlertDialog(
              title: Text('选择字体大小'),
              content: SingleChildScrollView(
                child: Column(
                  children: [
                    Slider(
                      value: tempFontSize,
                      min: 10.0,
                      max: 50.0,
                      onChanged: (double value) {
                        setStateDialog(() => tempFontSize = value); // 局部刷新
                      },
                    ),
                    Text('当前大小: ${tempFontSize.toStringAsFixed(1)}'),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  child: Text('取消'),
                  onPressed: () => Navigator.pop(context),
                ),
                TextButton(
                  child: Text('确定'),
                  onPressed: () {
                    setState(() {
                      // 重绘与myFontSize有关的页面。
                      myFontSize = tempFontSize;
                      bookProgress.fontSize = myFontSize;
                    }); // 最终确认时更新父状态
                    Navigator.pop(context);
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }


  String _currentInput = "0";
  void _showJumpSearchDialog(){
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setStateDialog) {
            return AlertDialog(
              title: Center(child: Text('输入跳转编号',style: TextStyle(fontSize: 16),)),
              content:  Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  decoration: InputDecoration(
                    labelText: '编号(章节名可能重复)',
                    hintText: '例如: 1, 2, 3...',
                    prefixIcon: Icon(Icons.search,size: 14,),
                    border: OutlineInputBorder(),
                    suffixIcon: IconButton(
                      icon: Icon(Icons.check,size: 14,), // 使用确认图标
                      onPressed: () {
                        // 获取当前输入的值并提交
                        FocusScope.of(context).requestFocus(FocusNode()); // 收起键盘
                        _jumpToChapterByNumber(_currentInput);
                      },
                    ),
                  ),
                  keyboardType: TextInputType.number,
                  onChanged: (value) {
                    _currentInput = value;
                  },
                  onSubmitted: (value) {
                    _jumpToChapterByNumber(value);
                  },
                ),
              ),
            );
          },
        );
      },
    );
  }
  void _jumpToChapterByNumber(String input) {
    try {
      int chapterNumber = int.parse(input);
      if (chapterNumber >= 0 && chapterNumber <= chapters.length-1) {
        navigateToChapter(chapterNumber); // 转换为0-based索引
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入0-${chapters.length}之间的数字')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('请输入有效的数字')),
      );
    }
  }


  bool viewMode = true;
  void showViewMenu(BuildContext context) {
    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(
        100, // 根据需要调整位置（左边距）
        100, // 根据需要调整位置（上边距）
        0,   // 右边距
        0,   // 下边距
      ),
      items: [
        PopupMenuItem(
          value: 'jump',
          child: Text('章节跳转'),
        ),
        PopupMenuItem(
          value: 'scroll',
          child: Text('滑动显示'), // 菜单项1
        ),
        PopupMenuItem(
          value: 'page',
          child: Text('分页模式'),
        ),
        PopupMenuItem(
          value: 'fontSize',
          child: Text('字体大小'),
        ),
      ],
    ).then((value) {
      if (value != null) {
        if (value == 'scroll') {
          setState(() {
            viewMode = true; // 设置为滑动模式
          });
        } else if (value == 'page') {
          setState(() {
            viewMode = false; // 设置为页面模式
          });
        }else if (value == 'fontSize'){
          _showFontSizeDialog();
        }else if (value == 'jump'){
          _showJumpSearchDialog();
        }
      }
    });
  }


  // 界面
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _showAppBar
          ? AppBar(
        toolbarHeight: 36,
        title: Text("$chapterTitle", style: TextStyle(fontSize: 16)),
        automaticallyImplyLeading: true,
        actions: [
          IconButton(onPressed: (){
            showViewMenu(context);
          }, icon: Icon(Icons.settings))
        ],
      )
          : null, // 根据 _showAppBar 决定是否显示 AppBar
      drawer: Drawer(
        elevation: 2,
        child: _buildChild(),
      ),
      body: GestureDetector(
        onTap: _toggleAppBar, // 点击页面时切换 AppBar 显示状态
        child: Column(
          children: [
            if(viewMode) ...[
              if(!_showAppBar)
                SizedBox(height: 50),
              Expanded(
                child: SingleChildScrollView(
                  controller: _scrollController,
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        Text(
                          chapters.isNotEmpty ? chapters[currentChapter].title : "章节加载中...",
                          style: TextStyle(fontSize: myFontSize),
                        ),
                        Text(
                          fileContent.isEmpty ? "章节内容为空" : fileContent,
                          style: TextStyle(fontSize: myFontSize),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            TextButton(
                              onPressed: currentChapter > 0 ? prePage : null,
                              child: Text("上一章节",style: TextStyle(fontSize: 16),),
                            ),
                            TextButton(
                              onPressed: currentChapter < (chapters.length) - 1 ? nextPage : null,
                              child: Text("下一章节",style: TextStyle(fontSize: 16),),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ] else ...[
              if(!_showAppBar)
                // Text("$currentPage",style: TextStyle(fontSize: myFontSize),),
                SizedBox(height: 30),
              Expanded(child: _pageViewShow()),
            ]
          ],
        ),
      ),

      bottomNavigationBar: _showAppBar
          ? BottomAppBar(
        height: 65,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            TextButton(
              onPressed: currentChapter > 0 ? prePage : null,
              child: Text("上一章节",style: TextStyle(fontSize: 16),),
            ),
            TextButton(
              onPressed: currentChapter < (chapters.length) - 1 ? nextPage : null,
              child: Text("下一章节",style: TextStyle(fontSize: 16),),
            ),
          ],
        ),
      )
          : null,
    );
  }
}

/*
* 这里的代码是设计阅读界面，实现的功能为：内容展示，章节显示，其他功能。
* */